<template>
  <div class="share-container">
    <Header title="我的分享" />

    <div class="share-content">
      <!-- 统计卡片 -->
      <div class="stats-card">
        <div class="stat-item">
          <div class="stat-value">{{ shareList.length }}</div>
          <div class="stat-label">总分享</div>
        </div>
        <div class="stat-divider"></div>
        <div class="stat-item">
          <div class="stat-value">{{ activeShares.length }}</div>
          <div class="stat-label">有效分享</div>
        </div>
        <div class="stat-divider"></div>
        <div class="stat-item">
          <div class="stat-value">{{ expiredShares.length }}</div>
          <div class="stat-label">已过期</div>
        </div>
      </div>

      <!-- 分享列表 -->
      <div class="share-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="share in shareList"
              :key="share.id"
              class="share-item"
              @click="showShareDetails(share)"
            >
              <div class="share-icon">
                <van-icon
                  name="share-o"
                  :color="getShareStatusColor(share)"
                  size="20"
                />
              </div>

              <div class="share-info">
                <div class="share-title">{{ share.shareName }}</div>
                <div class="share-meta">
                  <span class="share-time">{{ formatExpireTime(share.expireTime) }}</span>
                </div>
                <div class="share-stats">
                  <span>浏览 {{ share.viewCount || 0 }}</span>
                  <span>下载 {{ share.downloadCount || 0 }}</span>
                  <span>{{ getSharePermissionText(share.permissions) }}</span>
                </div>
              </div>

              <div class="share-actions">
                <van-icon
                  name="more-o"
                  @click.stop="showShareActions(share)"
                />
              </div>
            </div>

            <!-- 空状态 -->
            <van-empty
              v-if="shareList.length === 0 && !loading"
              description="暂无分享"
              image="default"
            />
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <!-- 分享操作面板 -->
    <van-action-sheet
      v-model:show="showActionSheet"
      :actions="shareActions"
      @select="handleShareAction"
      cancel-text="取消"
    />

    <!-- 分享详情弹窗 -->
    <van-popup
      v-model:show="showDetailsPopup"
      position="bottom"
      :style="{ height: '70%' }"
      round
    >
      <div v-if="selectedShare" class="share-details">
        <div class="details-header">
          <h3>分享详情</h3>
          <van-icon name="cross" @click="showDetailsPopup = false" />
        </div>

        <div class="details-content">
          <van-cell-group inset>
            <van-cell title="分享名称" :value="selectedShare.shareName" />
            <van-cell title="分享码" :value="selectedShare.shareCode" />
            <van-cell
              title="分享链接"
              :value="formatShareUrl(selectedShare.shareCode)"
              is-link
              @click="copyShareUrl(selectedShare.shareCode)"
            />
            <van-cell
              title="访问密码"
              :value="selectedShare.password || '无密码'"
            />
            <van-cell
              title="权限设置"
              :value="getSharePermissionText(selectedShare.permissions)"
            />
            <van-cell
              title="有效期"
              :value="formatExpireTime(selectedShare.expireTime)"
            />
            <van-cell title="浏览次数" :value="selectedShare.viewCount || 0" />
            <van-cell title="下载次数" :value="selectedShare.downloadCount || 0" />
          </van-cell-group>

          <div class="details-actions">
            <van-button
              block
              type="primary"
              @click="copyShareUrl(selectedShare.shareCode)"
            >
              复制分享链接
            </van-button>
            <van-button
              block
              @click="editShare(selectedShare)"
            >
              编辑分享设置
            </van-button>
            <van-button
              block
              type="danger"
              @click="cancelShare(selectedShare)"
            >
              取消分享
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { showToast, showConfirmDialog } from 'vant'
import Header from '@/components/Header.vue'
import { useShareStore } from '@/stores/share'
import type { ShareInfo } from '@/api/share'

const router = useRouter()
const shareStore = useShareStore()

// 使用 storeToRefs 保持响应式
const {
  shareList,
  loading
} = storeToRefs(shareStore)

// 方法不需要响应式
const {
  fetchMyShareList,
  removeShare,
  formatShareUrl,
  getSharePermissionText,
  formatExpireTime
} = shareStore

// 状态
const refreshing = ref(false)
const finished = ref(false)
const showActionSheet = ref(false)
const showDetailsPopup = ref(false)
const selectedShare = ref<ShareInfo | null>(null)

// 计算属性
const activeShares = computed(() =>
  shareList.value.filter((share: ShareInfo) => {
    if (!share.expireTime) return true
    return new Date(share.expireTime) > new Date()
  })
)

const expiredShares = computed(() =>
  shareList.value.filter((share: ShareInfo) => {
    if (!share.expireTime) return false
    return new Date(share.expireTime) <= new Date()
  })
)

// 分享操作选项
const shareActions = [
  { name: '查看详情', value: 'details' },
  { name: '复制链接', value: 'copy' },
  { name: '编辑设置', value: 'edit' },
  { name: '取消分享', value: 'cancel', color: '#ee0a24' }
]

// 方法
const onRefresh = async () => {
  refreshing.value = true
  try {
    await fetchMyShareList()
  } finally {
    refreshing.value = false
  }
}

const onLoad = async () => {
  // 这里可以实现分页加载
  finished.value = true
}

const showShareDetails = (share: ShareInfo) => {
  selectedShare.value = share
  showDetailsPopup.value = true
}

const showShareActions = (share: ShareInfo) => {
  selectedShare.value = share
  showActionSheet.value = true
}

const handleShareAction = (action: any) => {
  showActionSheet.value = false

  if (!selectedShare.value) return

  switch (action.value) {
    case 'details':
      showDetailsPopup.value = true
      break
    case 'copy':
      copyShareUrl(selectedShare.value.shareCode)
      break
    case 'edit':
      editShare(selectedShare.value)
      break
    case 'cancel':
      cancelShare(selectedShare.value)
      break
  }
}

const copyShareUrl = async (shareCode: string) => {
  try {
    const url = formatShareUrl(shareCode)
    await navigator.clipboard.writeText(url)
    showToast({
      type: 'success',
      message: '分享链接已复制'
    })
  } catch (error) {
    showToast({
      type: 'fail',
      message: '复制失败，请手动复制'
    })
  }
}

const editShare = (share: ShareInfo) => {
  router.push(`/share/edit/${share.id}`)
}

const cancelShare = async (share: ShareInfo) => {
  const confirmed = await showConfirmDialog({
    title: '确认取消分享',
    message: `确定要取消分享 "${share.shareName}" 吗？`
  })

  if (confirmed) {
    try {
      await removeShare(share.id)
      showDetailsPopup.value = false
    } catch (error) {
      showToast({
        type: 'fail',
        message: '取消分享失败'
      })
    }
  }
}

const getShareStatusColor = (share: ShareInfo) => {
  if (!share.expireTime) return '#1989fa'

  const now = new Date()
  const expireTime = new Date(share.expireTime)

  if (expireTime <= now) return '#969799'

  const timeLeft = expireTime.getTime() - now.getTime()
  const oneDayMs = 24 * 60 * 60 * 1000

  if (timeLeft <= oneDayMs) return '#ff976a'

  return '#1989fa'
}

onMounted(() => {
  fetchMyShareList()
})
</script>

<style scoped>
.share-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.share-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.stats-card {
  margin: 16px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1989fa;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #969799;
}

.stat-divider {
  width: 1px;
  background-color: #ebedf0;
  margin: 0 20px;
}

.share-list {
  flex: 1;
  margin: 0 16px 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.share-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.share-item:active {
  background-color: #f8f8f8;
}

.share-item:last-child {
  border-bottom: none;
}

.share-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.share-info {
  flex: 1;
  min-width: 0;
}

.share-title {
  font-size: 16px;
  color: #323233;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.share-meta {
  font-size: 12px;
  color: #969799;
  margin-bottom: 6px;
  display: flex;
  gap: 12px;
}


.share-stats {
  font-size: 12px;
  color: #969799;
  display: flex;
  gap: 8px;
}

.share-actions {
  margin-left: 12px;
  color: #969799;
  cursor: pointer;
}

.share-details {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebedf0;
}

.details-header h3 {
  margin: 0;
  font-size: 18px;
  color: #323233;
}

.details-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.details-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

:deep(.van-empty) {
  padding: 60px 20px;
}
</style>